<template>
  <div>
     <!-- 搜索框 -->
     <el-input v-model="searchKeyword" placeholder="按学号查询"
     clearable style="width: 25%; margin: 20px;"></el-input>
    <el-button type="primary" @click="search">
      <el-icon><Search /></el-icon>查询</el-button>
    <el-button @click="resetSearch">
      <el-icon><Refresh /></el-icon>重置</el-button>
    <el-button type="success" @click="exportBtn">
      <el-icon><Download /></el-icon>导出 Excel 表格</el-button>

    <!-- 学生信息表格 -->
    <el-table :data="tableData.slice(startIndex, endIndex)" border stripe v-loading="loading" :header-cell-style="{backgroundColor:'aliceblue',color:'#666'}">
      <el-table-column prop="id" label="学号" align="center" sortable/>
      <el-table-column prop="name" label="姓名" align="center"/>
      <el-table-column prop="college" label="学院" align="center"/>
      <el-table-column prop="type" label="助学贷款类型" align="center"/>
      <el-table-column label="操作" width="250px" align="center">
        <template #default="scope">
          <!-- 根据学生的审核状态显示不同内容 -->
          <template v-if="scope.row.greenState === '待审核'">
            <el-button type="primary" plain @click="showDetails(scope.row)">详情</el-button>
            <el-button type="success" plain @click="approveApplication(scope.row)">通过</el-button>
            <el-button type="danger" plain @click="rejectApplication(scope.row)">拒绝</el-button>
          </template>
          <template v-else>
            <!-- 已通过或已拒绝的文本 -->
            <el-button type="primary" plain @click="showDetails(scope.row)">详情</el-button>
            <span v-if="scope.row.greenState === '审核通过'" style="color: green;margin-left: 20px;">已通过</span>
            <span v-if="scope.row.greenState === '审核未通过'" style="color: red;margin-left: 20px;">已拒绝</span>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="currentPage"
      :page-size="pageSize"
      :total="tableData.length"
      @current-change="handlePageChange"
      style="margin-top: 20px;"
    ></el-pagination>

    <!-- 详情弹窗 -->
    <el-dialog v-model="dialogVisible" title="详细信息" width="50%">
      <!-- 学生详细信息表单 -->
      <el-form :model="selectedStudent" :rules="formRules" label-width="100px">
        <!-- 表单项配置... -->
        <el-form-item label="学号" prop="id" >{{ selectedStudent.id }}</el-form-item>
        <el-form-item label="姓名" prop="name">{{ selectedStudent.name }}</el-form-item>
        <el-form-item label="手机号" prop="phone">{{ selectedStudent.phone }}</el-form-item>
        <el-form-item label="学院" prop="college">{{ selectedStudent.college}}</el-form-item>
        <el-form-item label="年级" prop="grade">{{ selectedStudent.grade}}</el-form-item>
        <el-form-item label="评定学年" prop="year">{{ selectedStudent.year}}</el-form-item>
        <el-form-item label="助学贷款类型" prop="type">{{ selectedStudent.type}}</el-form-item>
        <el-form-item label="申请贷款金额" prop="amount">{{ selectedStudent.amount}} （单位：元）</el-form-item>
        <el-form-item label="申请陈述" prop="description" style="white-space: pre-wrap;word-wrap: break-word;">{{ selectedStudent.description}}</el-form-item>
        <el-form-item label="备注" prop="information" style="white-space: pre-wrap;word-wrap: break-word;">{{ selectedStudent.information}}</el-form-item>
      </el-form>
      <el-button type="primary" @click="closeDialog" style="width: 25%;">关闭</el-button>
    </el-dialog>
  </div>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus';
import { ShowApply,SearchApply,ChangeState } from '@/api/index/admin';
import * as XLSX from 'xlsx';

export default {
  data() {
    return {
      tableData: [],
      dialogVisible: false,
      loading: true,
      selectedStudent: {},
      formRules: {},
      searchKeyword: '',
      startIndex: 0,
      endIndex: 10, // 每页显示数量
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页显示数量
    };
  },
  created(){
    this.fetchDataFromBackend();
  },
  methods: {
    handlePageChange(newPage) {
      this.currentPage = newPage;
      this.startIndex = (newPage - 1) * this.pageSize;
      this.endIndex = this.startIndex + this.pageSize;
    },
    async fetchDataFromBackend() {
      try {
        this.loading = true;
        const response = await ShowApply();
        this.loading = false;
        // 假设返回的数据结构为数组
        this.tableData = response.data.data.map((item) => ({
          id: item.SNO,
          name: item.NAME,
          type: item.TYPE,
          phone:item.PHONE,
          college:item.COLLEGE,
          grade:item.GRADE,
          year:item.YEAR,
          amount:item.AMOUNT,
          description:item.DESCRIPTION,
          information:item.INFORMATION,
          greenState:item.GREENSTATE
        }));
      } catch (error) {
        console.error('Failed to fetch data from the backend:', error);
      }
    },
    search() {
      this.startIndex = 0; // 重置起始索引为第一页
      this.endIndex = this.pageSize; // 重置结束索引为每页显示数量
      if (this.searchKeyword) {
        const params = { id: this.searchKeyword };
        SearchApply(params)
          .then((res) => {
            if (res.data && res.data.data && res.data.data.length > 0) {
              this.tableData = res.data.data.map((item) => ({
                id: item.SNO,
                name: item.NAME,
                type: item.TYPE,
                phone:item.PHONE,
                college:item.COLLEGE,
                grade:item.GRADE,
                year:item.YEAR,
                amount:item.AMOUNT,
                description:item.DESCRIPTION,
                information:item.INFORMATION,
                greenState:item.GREENSTATE
              }));
            } else {
              this.tableData = []; // 清空表格数据
            }
          })
          .catch((error) => {
            console.error('Failed to search data:', error);
          });
      } else {
        this.fetchDataFromBackend(); // 显示全部数据
      }
    },
    resetSearch() {
      this.searchKeyword = ''; // 清空搜索框内容
      this.fetchDataFromBackend(); // 显示全部数据
    },
    exportBtn() {
      // 将 tableData 转换为 Excel 数据
      const excelData = this.tableData.map((item) => ({
        学号: item.id,
        姓名: item.name,
        学院: item.college,
        年级: item.grade,
        助学贷款类型: item.type,
        手机号: item.phone,
        评定学年: item.year,
        申请贷款金额: item.amount,
        申请陈述: item.description,
        备注: item.information
      }));
      // 创建工作簿
      const ws = XLSX.utils.json_to_sheet(excelData);
      // 创建工作簿名称
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, '绿色通道申请信息');
      // 导出 Excel 文件
      XLSX.writeFile(wb, '绿色通道申请信息.xlsx');
    },
    showDetails(row) {
      console.log(row);
      this.selectedStudent = row ;
      this.dialogVisible = true;
    },
    closeDialog() {
      this.dialogVisible = false;
    },
    approveApplication(row) {
      ElMessageBox.confirm(
          `是否确认通过 ${row.name} 学生的申请？`,
          '通过申请',
          {
            confirmButtonText: '通过',
            cancelButtonText: '取消',
            type: 'warning',
          }
        ).then(
          ChangeState({
            id:row.id, 
            status:row.greenState})
          .then(rep=>{
            let code=rep.data.code
            if(code===200){
              row.greenState='审核通过';
              this.$message({
                type: 'success',
                message: '已通过',
              })
            }else {
              ElMessage({
                type: 'error',
                message: '审核失败',
              })
            }
              })
        ).catch(()=>{
          ElMessage({
            type: 'error',
            message: '已取消',
          })
        }
        )
    },
    rejectApplication(row) {
        ElMessageBox.confirm(
          `是否确认拒绝 ${row.name} 学生的申请？`,
          '拒绝申请',
          {
            confirmButtonText: '拒绝',
            cancelButtonText: '取消',
            type: 'warning',
          }
        ).then(
          ChangeState({
            id:row.id, 
            status:row.greenState})
          .then(rep=>{
            let code=rep.data.code
            if(code===200){
              row.greenState='审核未通过';
              this.$message({
                type: 'success',
                message: '已拒绝',
              })
            }else {
              ElMessage({
                type: 'error',
                message: '审核失败',
              })
            }
              })
        ).catch(()=>{
          ElMessage({
            type: 'error',
            message: '已取消',
          })
        }
        )
    },
  },
  mounted() {
    this.fetchDataFromBackend();
  },
};
</script>

<style scoped>
::v-deep .el-form-item__content {
  display: block !important;
  text-align: left;
}
</style>